<template>
<el-form ref="ruleForm2" :model="ruleForm2" :rules="rules2" label-width="100px" class="demo-ruleForm">
  <el-form-item label="用户名" prop="checkName">
    <el-input v-model="ruleForm2.name"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="pass">
    <el-input  type="password" v-model="ruleForm2.password" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="确认密码" prop="checkPass">
    <el-input type="password" v-model="ruleForm2.checkPass" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="onSubmit('ruleForm2')">注册</el-button>
    <el-button type="primary" @click="goback">取消</el-button>
  </el-form-item>
</el-form>    
</template>
<script>
  export default {
    data() {
        var validatePass = (rule, value, callback) => {
          console.info(value);
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm2.checkPass !== '') {
            this.$refs.ruleForm2.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        console.info(value);
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm2.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      var validateName = (rule,value,callback) => {
        this.$http.get("/api/accounts/",{params:{'name':this.ruleForm2.name}}).then(res => {
          if(res.data.content != null){
            callback();
          }else{
            callback(new Error('该用户名已被注册'));
          }
        })
      }
      return {
        ruleForm2: {
          name: '',
          password: '',
          checkPass: ''
        },
        rules2:{
          checkName:[{validator: validateName,trigger:'change'}],
          pass:[ {validator: validatePass, trigger: 'blur'}],
          checkPass:[ {validator: validatePass2, trigger: 'blur'} ]
      }
      }
      
    },
    methods: {
      onSubmit(ruleForm2) {
        this.$refs[ruleForm2].validate((valid) => {
          if(valid){
            this.$http.post("/api/accounts/",this.ruleForm2).then(res => {
              console.info(res);
              if(res.status === '200'){
                alert('注册成功');
                this.$router.push({ path: "/"});
              }else{
                alert('注册失败');
              }
            })
          }
        })
      },
      goback() {
        this.$router.push({ path: "/" });
      }
    }
  }
</script>